extends Node2D

@onready var players: Node = $Players
const PLAYER = preload("res://player.tscn")
var peer = ENetMultiplayerPeer.new()

func _ready() -> void:
	var isServer = GlobalData.isServer
	if isServer:
		_on_create_button_down()
	else:
		_on_join_button_down()

# 创建服务器
func _on_create_button_down() -> void:
	# 创建监听的服务器
	var error = peer.create_server(5678)
	if error != OK:
		printerr("创建服务器失败，错误码", error)
		return
	multiplayer.multiplayer_peer = peer
	
	# 作为服务端，需要监听是否有别的客户端进行连接
	multiplayer.peer_connected.connect(_on_peer_connected)
	# 客户端创建成功后，在当前场景添加玩家
	add_player(multiplayer.get_unique_id())

func add_player(id: int) -> void:
	var player = PLAYER.instantiate()
	player.name = str(id)
	#player.position = Vector2(200,0)
	players.add_child(player)

# 当有新的客户端连接时，该方法会被触发
func _on_peer_connected(id: int) -> void:
	print("有玩家连接，ID为",id)
	add_player(id)

# 创建客户端并连接服务器
func _on_join_button_down() -> void:
	peer.create_client(GlobalData.serverIP, 5678)
	multiplayer.multiplayer_peer = peer
